/**
 * 通知系统 WebSocket 端点
 */
const connections = [];

/**
 * 处理通知系统 WebSocket 连接
 * @param {Object} request - WebSocket 请求对象
 */
function handleNotificationRequest(request) {
  console.log(`通知系统收到连接请求，来源: ${request.origin}`);
  
  // 接受连接
  const connection = request.accept(null, request.origin);
  connections.push(connection);
  console.log(`${new Date().toLocaleDateString()} 通知系统建立新连接，当前连接数: ${connections.length}`);
  
  // 发送欢迎消息
  connection.sendUTF(JSON.stringify({
    type: "system",
    message: "通知系统已连接"
  }));
  
  // 处理消息
  connection.on("message", (message) => {
    if (message.type === "utf8") {
      console.log(`通知系统收到消息: ${message.utf8Data}`);
      
      try {
        const data = JSON.parse(message.utf8Data);
        
        // 如果是广播通知
        if (data.type === "broadcast") {
          broadcastNotification(data.message, connection);
        }
      } catch (e) {
        console.error("解析消息失败:", e);
      }
    }
  });
  
  // 处理连接关闭
  connection.on("close", (reasonCode, description) => {
    // 从连接列表中移除
    const index = connections.indexOf(connection);
    if (index !== -1) {
      connections.splice(index, 1);
    }
    
    console.log(`${new Date().toLocaleDateString()} 通知系统连接关闭，当前连接数: ${connections.length}`);
  });
}

/**
 * 广播通知给所有客户端
 * @param {string} message - 通知消息
 * @param {Object} sender - 发送者连接对象（可选）
 */
function broadcastNotification(message, sender = null) {
  const notification = JSON.stringify({
    type: "notification",
    message: message,
    timestamp: new Date().toISOString()
  });
  
  connections.forEach((client) => {
    if ((!sender || client !== sender) && client.connected) {
      client.sendUTF(notification);
    }
  });
}

// 导出处理函数和广播函数
module.exports = {
  handleRequest: handleNotificationRequest,
  broadcast: broadcastNotification
};